#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''
命令行创建管理员用户,执行python createuser.py
'''
import os
import getpass
import importlib
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "component_management.settings")
import django
from django.contrib.auth import hashers

django.setup()
from django.conf import settings

from django import forms

hasher = getattr(hashers,settings.AUTH_HASHER)
app_name, model_name = settings.MY_AUTH_USER_MODEL.split('.')
models = importlib.import_module(app_name + '.models')
auth_model = getattr(models, model_name)  # 获取认证使用的model
check_fields = []
check_fields.append(auth_model.USERNAME_FIELD)
check_fields.append(auth_model.PASSWORD_FIELD)
check_fields.extend(auth_model.REQUIRED_FIELDS)



class CreateUserForm(forms.ModelForm):
    class Meta:
        model = auth_model
        fields = check_fields

if __name__ == "__main__":
    kwargs = {}
    username = input('%s:'%auth_model.USERNAME_FIELD).strip()
    kwargs[auth_model.USERNAME_FIELD] = username

    for field in auth_model.REQUIRED_FIELDS:
        input_val = input('%s:'%field).strip()
        kwargs[field] = input_val

    password = getpass.getpass('%s:'%auth_model.PASSWORD_FIELD).strip()
    hash_password = hasher.encode(hasher,password,hasher.salt(hasher))
    kwargs[auth_model.PASSWORD_FIELD] = hash_password
    user_obj = CreateUserForm(kwargs)
    if user_obj.is_valid():
        user_obj.instance.is_admin = True
        user_obj.save()
    else:
        print(user_obj.errors)